#include "Server.h"
//this function is called as a thread for each connection
void* read_loop_server(void* args) {
	Socket* sock=((struct read_loop_client_input*)args)->s;
	char buffer[MAX_MESSAGE_SIZE];
	struct global_header* global_head=(struct global_header*)&(buffer[0]);
	struct login_request* login_req=(struct login_request*)(buffer+sizeof(struct global_header));
	//TODO: put pointers of the header structs all pointing to (buffer+sizeof(struct global_header))
	//	This allows us to easily access the data, and makes modifying a header as easy as adding a variable to the struct
	
	unsigned int read_offset=0;
	int try_read=1;
	while(true) {
		unsigned int message_length_received=read_offset;
		if(try_read)
			message_length_received += sock->read(buffer+read_offset,MAX_MESSAGE_SIZE-read_offset);
		
		try_read=1;
		if(message_length_received<read_offset || (message_length_received==read_offset && !sock->is_alive() ) ) { //ie read() < 0 or it's broken
			//TODO: the socket is broken; do some cleanup
			return NULL;
		}
		
		unsigned int mes_len=ntohs(global_head->mess_size);
		if(mes_len>MAX_MESSAGE_SIZE) {
			//TODO: someone's sending bad headers or too much data; do some cleanup
			return NULL;
		}
		
		// make sure we have received the whole message //
		if(message_length_received<sizeof(struct global_header) || message_length_received<mes_len) {
			read_offset=message_length_received;
			continue;
		}
		
		int packet_type=ntohs(global_head->mess_type);
		switch(packet_type) {
			//TODO: implement actions to take for various messages
			case MT_LOGIN_REQ:
				break;
			default:
				//TODO: someone's sending bad headers; do some cleanup
				return NULL;
		}
		
		read_offset=0;
		// if we overlapped int reading the next packet, copy it to the beginning of buffer //
		
		//TODO: There's probably a more efficient way to do this rather than copying the whole rest of the buffer
		if(message_length_received>mes_len) {
			bcopy(buffer+mes_len,buffer,message_length_received-mes_len);
			read_offset=message_length_received-mes_len;
			try_read=0;
		}
	}
	return NULL;
}
